<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm
          :fieldList="fieldList"
          :formOption="optionsData"
          :formData="form"
        >
          <template #create_user="{ value, input }">
            <VCascader
              :model-value="value"
              @update:model-value="input"
              collapse-tags
              class="w-[200px]"
              placeholder="创建人"
            />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VActionBar :actions="actions" />
      </template>
      <template #operation="{ row }">
        <el-button
          v-hasPermi="[logisticsSettingsAuthList.payment_setting.edit]"
          link
          type="primary"
          @click="handleEdit(row)"
        >
          编辑
        </el-button>
        <el-button
          link
          :type="row.status === 0 ? 'primary' : 'danger'"
          @click="handleStatusRow(row)"
          v-hasPermi="[
            row.status === 0
              ? logisticsSettingsAuthList.payment_setting.enable
              : logisticsSettingsAuthList.payment_setting.disabled,
          ]"
        >
          {{ { 0: "启用", 1: "禁用" }[row.status] }}
        </el-button>
        <el-button link type="primary" @click="handleLog(row)">
          日志
        </el-button>
      </template>
    </VTable>
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
    <Add
      :id="addId"
      v-model="addVisible"
      :option="optionsDataAll"
      @close="addId = null"
      @refresh="refresh"
    />
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="logistics.bp-config"
      :business_id="logId"
      @close="logId = ''"
    />
  </VPage>
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import { optMonth, optLimit } from "./components/Add/data.js";
import Log from "@/components/Log/index.vue";
import XForm from "@/components/XForm/index.vue";
import { bpConfigStatus } from "./api.js";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
import DerivedCenter from "@/components/DerivedCenter";
import { config_name } from "@/config/export.js";
import { logisticsSettingsAuthList } from "@/Auth/logistics-settings.js";
import { useEnumSelect } from "@/hooks/useEnumSelect.js";
import Add from "./components/Add/index";
import { bpConfigList } from "./api.js";
const { proxy } = getCurrentInstance();
const tableRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: { type: "create_time", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    { fixed: "left", width: 50, title: "编号", type: "seq" },
    { fixed: "left", title: "账期名称", minWidth: 260, field: "bp_name" },
    { title: "账期类型", width: 120, field: "bp_type" },
    {
      title: "状态",
      width: 100,
      field: "status",
      slots: {
        default: ({ row }) => {
          return <VstatusRender code={row} />;
        },
      },
    },
    { title: "更新人", width: 170, field: "update_user" },
    { title: "更新时间", width: 170, field: "update_time" },
    { title: "备注", minWidth: 220, field: "remark" },
    {
      title: "操作",
      width: 160,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return bpConfigList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});

const publicStyle = { style: { width: "240px" } };
const fieldList = [
  { field: "bp_name", placeholder: "账期名称", type: "input", ...publicStyle },
  {
    field: "create_user",
    slot: "create_user",
  },
  {
    field: "bp_type",
    type: "select",
    originOption: "logistics_bp_type",
    ...publicStyle,
    options: {
      placeholder: "账期类型",
    },
  },
  {
    field: "status",
    type: "select",
    ...publicStyle,
    options: {
      placeholder: "状态",
      data: [
        { label: "启用", value: 1 },
        { label: "禁用", value: 0 },
      ],
    },
  },
  {
    field: "dateRange",
    type: "dateTimeRange",
    style: { width: "360px" },
    itemProps: {
      startPlaceholder: "更新最早时间",
      endPlaceholder: "更新最晚时间",
    },
  },
];

const { options: optionsData } = useEnumSelect({
  params: [
    "logistics_bp_type",
    "logistics_bp_settle_type",
    "logistics_bp_time_type",
  ],
});
const optionsDataAll = computed(() => ({
  ...optionsData.value,
  optMonth,
  optLimit,
}));
const addId = ref(null);
const addVisible = ref(false);
const handleAdd = () => {
  addVisible.value = true;
};
const handleEdit = (item) => {
  addId.value = item.id;
  addVisible.value = true;
};

const logId = ref("");
const logVisible = ref(false);
const handleLog = (item) => {
  logId.value = item.id;
  logVisible.value = true;
};

const handleStatus = (status) => {
  const rows = getTableSelect(tableRef.value);
  if (!rows.length) return ElMessage.warning("请至少选择一条数据!");
  handleStatusReq(rows, status);
};
const handleStatusRow = (row) => {
  handleStatusReq([row.id], row.status ? 0 : 1);
};
const handleStatusReq = (id, flag) => {
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认{flag ? "启用" : "禁用"}选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await bpConfigStatus({ id, status: flag ? 1 : 0 });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};

const refresh = () => {
  tableRef?.value.$table.commitProxy("query");
};

//导出中心
const DerivedCenterRef = ref();
const handleExport = () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value?.open({
    tag_name: config_name["logistics_settings"]["export_logistics_bp_config"],
    condition,
  });
};
const actions = [
  {
    label: "新增",
    icon: "add2",
    type: "primary",
    fn: handleAdd,
    permission: [logisticsSettingsAuthList.payment_setting.add],
  },
  {
    label: "启用",
    icon: "state_finish_line",
    fn: () => handleStatus(true),
    permission: [logisticsSettingsAuthList.payment_setting.enable],
  },
  {
    label: "禁用",
    icon: "state_disabled",
    fn: () => handleStatus(false),
    permission: [logisticsSettingsAuthList.payment_setting.disabled],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [logisticsSettingsAuthList.merchant.export],
  },
];
</script>
